package com.aaa.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * {@code @BelongsProject:} security03
 * {@code @BelongsPackage:} com.aaa.util
 * {@code @Author:} ql
 * {@code @CreateTime:} 2023-03-10  08:57
 * {@code @Description:} TODO
 * {@code @Version:} 1.0
 */
public class JwtUtil {
    private static final String secret="qy160-ql";
    public static void main(String[] args) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("name","ql");
        String token = createJWT(map);
        System.out.println("token = " + token);
    }
/* 获取getToken */
    public static String createJWT(Map<String,Object> map){

        Calendar instance = Calendar.getInstance();
        instance.set(Calendar.SECOND,7200); //失效时间
        Date time = instance.getTime();

        return JWT.create()
                .withHeader(map)
                .withIssuedAt(new Date()) //签发时间
                .withExpiresAt(time) //过期时间
                .withSubject("分离")
                .withClaim("map", map) //自定义
                .sign(Algorithm.HMAC256(secret));
    }

    /* 检查Token */
    public static Boolean verifyToken(String token){
        try {
            Verification require = JWT.require(Algorithm.HMAC256(secret));
            require.build().verify(token);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    //获取token中指定的数据
    public static Map<String,Object> getTokenChaim(String token){
        Verification require = JWT.require(Algorithm.HMAC256(secret));
        DecodedJWT verify = require.build().verify(token);
        return verify.getClaim("map").asMap();
    }
}
